#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Project ：t-player
@File    ：Player.py
@Author  ：kehao
@Date    ：2021/8/1 22:10
"""
import logging
import os
import random
import time

import pygame
from pygame.event import EventType

from download import download

logger = logging.getLogger()

SONG_FINISHED = pygame.USEREVENT + 1


class Player:
    def __init__(self, data):
        self.data = data
        self.exit_flag = False
        pygame.init()
        pygame.mixer.init(channels=2)
        pygame.mixer.music.set_endevent(SONG_FINISHED)
        pygame.mixer.music.set_volume(0.2)

    def play_one(self):
        try:
            self.unload()
            music = self.next_music()
            name = music['name']
            url = music['url']
            music_path = download(name, url)
            if not os.path.exists(music_path):
                pygame.event.post(EventType(SONG_FINISHED))
                return

            logger.info('playing %s', name)
            pygame.mixer.music.load(music_path)
            pygame.mixer.music.play()
        except BaseException as err:
            logger.error(str(err))
            pygame.event.post(EventType(SONG_FINISHED))

    def play(self):
        self.play_one()

        while not self.exit_flag:
            time.sleep(1)
            if not pygame.get_init():
                break
            event = pygame.event.wait(1)
            if event.type == SONG_FINISHED:
                self.play_one()

    def next_music(self):
        idx = random.randint(0, len(self.data) - 1)
        return self.data[idx]

    def unload(self):
        pygame.mixer.music.stop()
        pygame.mixer.music.unload()

    def pause(self):
        pygame.mixer.music.pause()
        return

    def unpause(self):
        pygame.mixer.music.unpause()
        return

    def exit(self):
        self.exit_flag = True
        pygame.quit()
        return

    def plus_vol(self):
        cur_vol = pygame.mixer.music.get_volume()
        cur_vol += 0.1
        if cur_vol > 1:
            cur_vol = 1
        pygame.mixer.music.set_volume(cur_vol)

    def sub_vol(self):
        cur_vol = pygame.mixer.music.get_volume()
        cur_vol -= 0.1
        if cur_vol < 0:
            cur_vol = 0
        pygame.mixer.music.set_volume(cur_vol)
